package com.springMVCStudy.controller;

import com.springMVCStudy.pojo.User;
import jakarta.validation.constraints.NotBlank;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
@ResponseBody
public class UserController {

    @RequestMapping("/data")
    public String data() {
        // 空指针异常
        String name = null;
        name.toString();
        return name;
    }

    @RequestMapping("/data1")
    public String data1() {
        // 算术异常
        int wrong = 1/0;
        return "ok";
    }

    @RequestMapping("/data2")
    public String data2() {
        System.out.println("data2");
        return "data2";
    }


    @RequestMapping("/data3")
    public String data3() {
        System.out.println("data3");
        return "data3";
    }

    /*
    接收用户数据，用户有校验注解
    实体类属性添加注解@Validated，实体类属性上的校验注解才会生效

    校验后接收参数报错，自定义返回结果
    捕捉错误信息，绑定错误信息：
    1、handler(校验对象, BindingResult result)，要求bindingResult在形参列表中必须紧挨着校验对象
    2、bindingResult获取绑定错误
     */
    @PostMapping("/register")
    public Object register(@Validated @RequestBody User user, BindingResult result, /*这个不生效*/ @NotBlank String verificationCode) {

        // 如果报错，自定义返回内容
        if (result.hasErrors()) {
            Map data = new HashMap();
            data.put("code", 400);
            data.put("msg", "参数校验异常");
            return data;
        }

        System.out.println("user = " + user);
        return user;
    }

}
